package com.example.validatestudy.demos.common;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class RequestCounter {

    private final AtomicInteger requestCount = new AtomicInteger(0);
    private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    public void startMonitoring() {
        executor.scheduleAtFixedRate(() -> {
            int currentCount = requestCount.getAndSet(0); // 获取并重置计数器
            System.out.printf("接口每秒请求数: %d%n", currentCount);
            // 这里可以进一步将统计结果记录到日志、数据库或发送至监控系统
        }, 0, 1, TimeUnit.SECONDS);
    }

    public void incrementRequestCount() {
        requestCount.incrementAndGet(); // 每当接口被调用时，递增计数器
    }

    public void stopMonitoring() {
        executor.shutdownNow();
    }
}

